import re
import sys
import ldap

l = ldap.initialize("ldap://ldap.isu.edu")
base = "o=isu.edu,o=isp"

def show(result):
	if(result):
		 return result[0][1]['mail'][0]#,'\t\t\t', result[0][1]['cn'][0]

def query(first,last):
	result = l.search_s(base,ldap.SCOPE_SUBTREE, '(&(sn=%s)(givenName=%s))' % (last,first), ['cn','mail'])
	return show(result)

		
def search(raw):
	if (raw):
		raw = raw.replace("'","")
		raw = re.sub('\sand\s',' & ',raw)
		if (re.match('([a-zA-Z]+),\s+([a-zA-Z]+)(\s+([a-zA-Z])\.?)?',raw)):
			#print names
			names = re.findall('(\w+),\s+(\w+)(\s+(\w)\.)?',raw)
			#print names
			id = []
			for name in names:
				id.append(query(name[1],name[0]))
			return id
		
		if (re.match('([A-Za-z]+)(\s+[A-Za-z]\.?)?\s+([A-Za-z]+)',raw)):
			names = re.findall('(\w+)(\s+\w\.?)?\s+(\w+)',raw)
			#print names
			id = []
			for name in names:
				id.append(query(name[0],name[2]))
			return id

if __name__ == "__main__":
	search(sys.argv[1])
	

